import { Component, OnInit, Input } from '@angular/core';
import { TreeNode } from 'primeng/primeng';
import { ConfigService } from './cfg.service';
import { DialogService } from 'primeng/primeng';
import { TaskListAddComponent } from './tasklist-add.component';

@Component({
  selector: 'tasklist-config',
  templateUrl: './tasklist-cfg.component.html',
  styleUrls: ['./tasklist-cfg.component.scss'],
  providers: [ConfigService]
})
export class TaskListConfigComponent implements OnInit {
  @Input()
  systemUrl: string = '';

  currentBiz: number = 0;
  @Input()
  set bizId(bizId: number) {
    if (!bizId || !this.systemUrl) return;
    this.currentBiz = bizId;
    this.initTree(null);
  }
  get bizId(): number { return this.currentBiz; }

  currentProcDefId: number = 0;
  @Input()
  set procDefId(procDefId: number){
    if(procDefId){
      this.currentProcDefId = procDefId;
    }
  }

  currentTaskListGroupId: number = 0;
  @Input()
  set taskListGroupId(taskListGroupId: number){
    if (!taskListGroupId || !this.systemUrl) return;
    this.currentTaskListGroupId = taskListGroupId;
    this.initTree(null);
  }

  loading: boolean = true;
  transTree: TreeNode[];
  selectedNode: TreeNode;
  taskListId: number = 0;

  constructor(
    private configService: ConfigService,
    private dialogService: DialogService) {
    configService.routeMsgPush$.subscribe(data => this.initTree(data));
  }

  ngOnInit() {
    this.initTree(null);
  }

  /**初始化树节点 */
  initTree(taskListId) {
    this.loading = true;
    this.configService.getTaskListTree(this.currentBiz, this.currentTaskListGroupId, this.systemUrl).subscribe(data => {
      this.loading = false;
      this.transTree = data;
      if (data.length > 0 && data[0].children.length > 0) {
        this.selectedNode = data[0].children[0];
        this.nodeSelect(null);
      } else {
        this.taskListId = 0;
      }
    })
  }
  /**节点选择事件 */
  nodeSelect(event) {
    this.taskListId = this.selectedNode['id'];
  }

  /**新增开箱 */
  addTaskList() {
    const ref = this.dialogService.open(TaskListAddComponent, {
      header: '添加栏目',
      width: '450px',
      contentStyle: { 'height': '250px' },
      data: {
        'systemUrl': this.systemUrl,
        'bizId': this.bizId,
        'taskListGroupId': this.currentTaskListGroupId
      }
    });
    ref.onClose.subscribe(data => {
      if (data) {
        this.loading = true;
        this.initTree(data);
      }
    });
  }


}
